#pragma once
#include <iostream>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>



#include "Log.hpp"
#include "InetAddr.hpp"
#include "Threadpool.hpp"
const static int defaultsockfd = -1;
const static int gbacklog = 16;

using func1 = std::function<std::string(std::string)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

class TcpServer;
class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr,TcpServer* s) : sockfd(fd), clientaddr(addr),self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer* self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port,func1 func) : _port(port), _func_t(func),_listensock(defaultsockfd), _isrunning(false) {}

    void InitServer()
    {
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "_listensock create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "_listensock create success sock is %d: \n", _listensock);

        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "_listensock bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "_listensock bind success sock is %d: \n", _listensock);
        // 3. tcp是面向连接的，所以通信之前，必须先建立连接。服务器是被连接的
        //    tcpserver 启动，未来首先要一直等待客户的连接到来
        n = ::listen(_listensock, gbacklog);
        if (n < 0)
        {
            LOG(FATAL, "_listensock listen error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "_listensock listen success sock is %d: \n", _listensock);
    }

    void Service(int sockfd, InetAddr addr)
    {
        LOG(DEBUG, "get a new line from [%s : %d] fd : %d\n", addr.Ip().c_str(), addr.Port(), sockfd);
        std::string clientaddr = "[" + addr.Ip() + ":" + std::to_string(addr.Port()) + "]";
        while (true)
        {
            char buffer[1024];
            std::string req;
            ssize_t n = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                // buffer[n] = 0;
                cout << clientaddr << "--------" <<buffer << endl;
                // std::string ecoh_string = "[ server say ]# ";
                buffer[n] = 0;
                req += buffer;
                std::string echo_string = _func_t(req);
                ::write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                // client 退出&&关闭连接了
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n", clientaddr.c_str());
                break;
            }
        }
        ::close(sockfd);
    }

    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->Service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error %d \n ", sockfd);
                continue;
            }
            // Version 0 : 一次只能处理一个请求 --- 不可能
            // Service(sockfd, InetAddr(peer));

            // Version 1: 采用多进程
            // pid_t id = fork();
            // if (id == 0)
            // {
            //     // child 关心sock 不关心 listensock
            //     ::close(_listensock);
            //     if (fork() > 0)
            //         exit(0); // 这里退出的是子进程，子进程退出下面会有父亲进程等着他

            //     Service(sockfd, InetAddr(peer)); // 孙子进程 -- 孤儿进程 --- 系统领养
            //     exit(0);// 这里退出的是孙子进程，孙子进程退出下面会有bash进程等着他
            //     //所以自己不用管
            // }
            // // // father： 关心listensock，不关心sockfd
            // ::close(sockfd);
            // waitpid(id, nullptr, 0);

            // version 2: 采用多线程
            pthread_t t;
            ThreadData *td = new ThreadData(sockfd, InetAddr(peer),this);
            pthread_create(&t, nullptr, HandlerSock, td);

            // version 3: 采用线程池版本
            // std::function<void()> t = std::bind(&TcpServer::Service,this,sockfd,InetAddr(peer));
            // ThreadPool<std::function<void()>>::GetInstance()->Enqueue(t);
        }
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isrunning;
    func1 _func_t;
};